<template>
    <div>
        <el-row>
            <el-col :span="24">
                <h4>{{ selectdFieldShow }}</h4>
            </el-col>
        </el-row>
        <div class="buttonBar">
            <div class="buttonList">
                <el-button type="primary" :disabled="hasSelectdField" @click="selecPrevios">《《 查询来源字段</el-button>
                <el-button type="primary" @click="dataFieldFormVisible = true">新增关联字段</el-button>
                <el-button type="primary" :disabled="hasSelectdField" @click="selectNext">查询衍生字段 》》</el-button>
            </div>
        </div>
        <div class="container">
            <div><!-- 这一层div必须有，不然排版会乱 -->
                <div v-for="item in items" :key="item.currentLevel" class="item">
                    <link-field-module @selectOneDataField="selectdDataField" :currentItem="item"
                        :currentSelectedDataField="selectdFieldInfo"></link-field-module>
                </div>
            </div>
        </div>
    </div>



    <!--- 新增数据字段的对话框 -->
    <el-dialog v-model="dataFieldFormVisible" title="新增关联数据字段">
        <el-text class="highShow">当前添加的数据库字段将自动与与选中的数据库字段关联</el-text>
        <el-row>
            <el-col :span="24">
                <el-radio v-model="addLinkType" label="to" size="large">由此字段衍生</el-radio>
                <el-radio v-model="addLinkType" label="from" size="large">此字段的来源</el-radio>
            </el-col>
        </el-row>
        <el-form :model="dataFieldForm">
            <el-form-item label="字段名:" :label-width="formLabelWidth">
                <el-input v-model="dataFieldForm.fieldName" />
            </el-form-item>
            <el-form-item label="字段描述:" :label-width="formLabelWidth">
                <el-input v-model="dataFieldForm.fieldDesc" />
            </el-form-item>
            <el-form-item label="字段类型:" :label-width="formLabelWidth">
                <el-input v-model="dataFieldForm.fieldType" />
            </el-form-item>
            <el-form-item label="表名:" :label-width="formLabelWidth">
                <el-input v-model="dataFieldForm.tableName" />
            </el-form-item>
            <el-form-item label="数据库名:" :label-width="formLabelWidth">
                <el-input v-model="dataFieldForm.databaseName" />
            </el-form-item>
            <el-form-item label="数据库类型:" :label-width="formLabelWidth">
                <el-input v-model="dataFieldForm.databaseType" />
            </el-form-item>
            <el-form-item label="数据库描述:" :label-width="formLabelWidth">
                <el-input v-model="dataFieldForm.databaseDesc" />
            </el-form-item>
            <!-- <el-form-item label="Zones" :label-width="formLabelWidth">
          <el-select v-model="form.region" placeholder="Please select a zone">
            <el-option label="Zone No.1" value="shanghai" />
            <el-option label="Zone No.2" value="beijing" />
          </el-select>
        </el-form-item> -->
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dataFieldFormVisible = false">取消</el-button>
                <el-button type="primary" @click="saveDataField" :loading="loading">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
// import axios from 'axios'
import { ElNotification, ElMessage } from 'element-plus'
import LinkFieldModule from '@/components/link_field/LinkFIeldModule.vue'
import axios from 'axios'

export default {
    name: 'LinkField',
    components: {
        LinkFieldModule
    },
    props: {
        // 打开此页面时传入的数据库字段
        dataField: {}
    },
    data() {
        return {
            items: [],
            selectdFieldShow: "当前还未选中任何一个字段",
            selectdFieldInfo: null,
            hasSelectdField: true,
            currentCoreLevel: 0,
            dataFieldFormVisible: false,
            dataFieldForm: {
                fieldName: "",
                fieldDesc: "",
                fieldType: "",
                tableName: "",
                databaseName: "",
                databaseType: "",
                databaseDesc: ""
            },
            addLinkType: "to"
        }
    },
    mounted() {
        this.items.push({
            // 当前这一层级是由哪个字段查询来的，可能是from也可能是to，看sourceType的值
            sourceDataField: [this.$route.query],
            // from：是从“sourceDataField”衍生出来的字段
            // to：是“sourceDataField”的来源字段
            // core：当前页面查询的字段全部由此字段衍生或构成自此段，此时“sourceDataField”为自己本身
            sourceType: "core",
            // 当前层级是从哪个字段form/to来的，core类型的此值为空
            sourceField: "",
            // 当前层级的唯一标识
            currentLevel: 0
        })
    },
    // watch的所有方法，第一个参数为新值，第二个参数为旧值
    watch: {
        selectdFieldInfo(n) {
            if (n) {
                this.hasSelectdField = false
                let descShow = this.selectdFieldInfo.selectd.fieldDesc ? this.selectdFieldInfo.selectd.fieldDesc : '';
                this.selectdFieldShow = "当前选中: LevelName = " + this.selectdFieldInfo.levelName + " 的 " + this.selectdFieldInfo.selectd.fieldName + " (" + descShow + ")"
            } else {
                this.hasSelectdField = true
                this.selectdFieldShow = "当前还未选中任何一个字段"
            }
        }
    },
    methods: {
        // 子组件通知父组件，有一个字段被选中了
        selectdDataField(data) {
            this.selectdFieldInfo = data
        },
        saveDataField() {
            this.loading = true
            var postData = this.dataFieldForm
            postData.linkType = this.addLinkType
            postData.linkFieldId = this.selectdFieldInfo.selectd.id
            axios.post('/easy_metadata/data_field/add', postData)
                .then(response => {
                    this.loading = false;
                    if (response.data.data) {
                        this.dataFieldFormVisible = false
                        this.dataFieldForm.fieldName = ""
                        this.dataFieldForm.fieldDesc = ""
                        this.dataFieldForm.fieldType = ""
                        this.dataFieldForm.tableName = ""
                        this.dataFieldForm.databaseName = ""
                        this.dataFieldForm.databaseType = ""
                        this.dataFieldForm.databaseDesc = ""
                        ElMessage('添加成功')
                    } else {
                        ElNotification({
                            title: '保存失败',
                            message: '发生异常，保存失败',
                            type: 'error',
                        })
                    }
                })
                .catch(error => {
                    this.loading = false;
                    console.log(error)
                    ElNotification({
                        title: '保存失败',
                        message: '发生异常，保存失败',
                        type: 'error',
                    })
                })
        },
        selectNext() {
            if (!this.selectdFieldInfo) {
                ElMessage('未选中字段')
                return
            } else {
                // 如果当前被选中的字段是一个‘to’类型中的字段，那所有当前已经显示的数据将会清除
                if (this.selectdFieldInfo.levelName < this.currentCoreLevel) {
                    this.items = [];
                    this.items.push({
                        // 当前这一层级是由哪个字段查询来的，可能是from也可能是to，看sourceType的值
                        sourceDataField: [{
                            "id": this.selectdFieldInfo.selectd.id,
                            "fieldName": this.selectdFieldInfo.selectd.fieldName,
                            "fieldDesc": this.selectdFieldInfo.selectd.fieldDesc,
                            "fieldType": this.selectdFieldInfo.selectd.fieldType,
                            "createdDt": this.selectdFieldInfo.selectd.createdDt,
                            "tableName": this.selectdFieldInfo.selectd.tableName,
                            "updatedDt": this.selectdFieldInfo.selectd.updatedDt,
                            "databaseDesc": this.selectdFieldInfo.selectd.databaseDesc,
                            "databaseName": this.selectdFieldInfo.selectd.databaseName,
                            "databaseType": this.selectdFieldInfo.selectd.databaseType
                        }],
                        // from：是从“sourceDataField”衍生出来的字段
                        // to：是“sourceDataField”的来源字段
                        // core：当前页面查询的字段全部由此字段衍生或构成自此段，此时“sourceDataField”为自己本身
                        sourceType: "core",
                        // 当前层级是从哪个字段form/to来的，core类型的此值为空
                        sourceField: "",
                        // 当前层级的唯一标识
                        currentLevel: this.selectdFieldInfo.levelName
                    })
                    this.currentCoreLevel = this.selectdFieldInfo.levelName
                }
                axios.get('/easy_metadata/link/field/by_from', {
                    params: { "fieldId": this.selectdFieldInfo.selectd.id }
                })
                    .then(response => {
                        if (response.data.data) {
                            if (this.items.length > 1) {
                                // 剔除levelName比当前选中字段的LevelName大的数据
                                this.items = this.items.filter((element) => element.currentLevel <= this.selectdFieldInfo.levelName)
                            }
                            let index = this.currentCoreLevel;
                            this.items.forEach(element => index = index > element.currentLevel ? index : element.currentLevel)
                            if (response.data.data.length > 0) {
                                this.items.push({
                                    // 当前这一层级是由哪个字段查询来的，可能是from也可能是to，看sourceType的值
                                    sourceDataField: response.data.data,
                                    // from：是从“sourceDataField”衍生出来的字段
                                    // to：是“sourceDataField”的来源字段
                                    // core：当前页面查询的字段全部由此字段衍生或构成自此段，此时“sourceDataField”为自己本身
                                    sourceType: "from",
                                    // 当前层级是从哪个字段form/to来的，core类型的此值为空
                                    sourceField: this.selectdFieldInfo.selectd,
                                    // 当前层级的唯一标识
                                    currentLevel: index + 1
                                })
                            } else {
                                ElMessage({
                                    message: "当前字段无衍生字段",
                                    type: 'warning'
                                })
                            }
                        }
                    })
                    .catch(error => {
                        // 处理请求失败的情况
                        console.error(error);
                    });
            }
        },

        selecPrevios() {
            if (!this.selectdFieldInfo) {
                ElMessage('未选中字段')
                return
            } else {
                // 如果当前被选中的字段是一个‘from’类型中的字段，那所有当前已经显示的数据将会清除
                if (this.selectdFieldInfo.levelName > this.currentCoreLevel) {
                    this.items = [];
                    this.items.push({
                        // 当前这一层级是由哪个字段查询来的，可能是from也可能是to，看sourceType的值
                        sourceDataField: [{
                            "id": this.selectdFieldInfo.selectd.id,
                            "fieldName": this.selectdFieldInfo.selectd.fieldName,
                            "fieldDesc": this.selectdFieldInfo.selectd.fieldDesc,
                            "fieldType": this.selectdFieldInfo.selectd.fieldType,
                            "createdDt": this.selectdFieldInfo.selectd.createdDt,
                            "tableName": this.selectdFieldInfo.selectd.tableName,
                            "updatedDt": this.selectdFieldInfo.selectd.updatedDt,
                            "databaseDesc": this.selectdFieldInfo.selectd.databaseDesc,
                            "databaseName": this.selectdFieldInfo.selectd.databaseName,
                            "databaseType": this.selectdFieldInfo.selectd.databaseType
                        }],
                        // from：是从“sourceDataField”衍生出来的字段
                        // to：是“sourceDataField”的来源字段
                        // core：当前页面查询的字段全部由此字段衍生或构成自此段，此时“sourceDataField”为自己本身
                        sourceType: "core",
                        // 当前层级是从哪个字段form/to来的，core类型的此值为空
                        sourceField: "",
                        // 当前层级的唯一标识
                        currentLevel: this.selectdFieldInfo.levelName
                    })
                    this.currentCoreLevel = this.selectdFieldInfo.levelName
                }
                axios.get('/easy_metadata/link/field/by_to', {
                    params: { "fieldId": this.selectdFieldInfo.selectd.id }
                })
                    .then(response2 => {
                        if (response2.data.data) {
                            if (this.items.length > 1) {
                                // 剔除levelName比当前选中字段的LevelName小的数据
                                this.items = this.items.filter((element) => element.currentLevel >= this.selectdFieldInfo.levelName)
                            }
                            let index = this.currentCoreLevel;
                            this.items.forEach(element => index = index < element.currentLevel ? index : element.currentLevel)
                            if (response2.data.data.length > 0) {
                                let item = {
                                    // 当前这一层级是由哪个字段查询来的，可能是from也可能是to，看sourceType的值
                                    sourceDataField: response2.data.data,
                                    // from：是从“sourceDataField”衍生出来的字段
                                    // to：是“sourceDataField”的来源字段
                                    // core：当前页面查询的字段全部由此字段衍生或构成自此段，此时“sourceDataField”为自己本身
                                    sourceType: "to",
                                    // 当前层级是从哪个字段form/to来的，core类型的此值为空
                                    sourceField: this.selectdFieldInfo.selectd,
                                    // 当前层级的唯一标识
                                    currentLevel: index - 1
                                }
                                this.items.unshift(item)
                            } else {
                                ElMessage({
                                    message: "当前字段无来源字段",
                                    type: 'warning'
                                })
                            }
                        }
                    })
                    .catch(error => {
                        // 处理请求失败的情况
                        console.error(error);
                    });
            }
        }
    }
}
</script>

<style>
.buttonBar {
    width: 100%;
    margin-top: 10px;
}

.buttonList {
    margin: 0 auto;
}

.container {
    display: flex;
    flex-direction: space-between;
    overflow-y: scroll;
    white-space: nowrap;
}

.item {
    width: 800px;
    background-color: #ffffff;
    display: inline-block;
    margin: 0px 3px;
}

.highShow {
    color: red;
}
</style>